import axios from "axios";

class HttpRequest {
  constructor(options) {
    this.http = axios.create(options);
    this.options = options;
  }
  // get请求
  get(url, data) {
    return this.request({
      method: "GET",
      url: url,
      params: {
        data,
      },
    });
  }
  // post请求
  post(url, data) {
    return this.request({
      method: "POST",
      url: url,
      data: {
        data,
      },
    });
  }
  // 并发请求
  all(requestList) {
    return axios.all(requestList).then(
      axios.spread(function (...res) {
        return res;
      })
    );
  }
  // request请求
  request(payload) {
    const { beforeRequest, beforeResponse, errorCapture } =
      this.options.extraConfig;

    const http = beforeRequest(this.http, payload); //请求前处理

    return http
      .request(payload)
      .then((res) => {
        return beforeResponse(res);
      })
      .catch((err) => {
        console.log("错误的代码:" + err);
        errorCapture(err);
      });
  }
}

export default HttpRequest;
